package top.shaozuo.simple.user.web.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@WebListener
public class ServletConfigHolder implements ServletRequestListener {

	 private static ThreadLocal<Config> configHolder = 
	            new ThreadLocal<>();
	 
	 private static final Logger logger = LoggerFactory.getLogger(ServletConfigHolder.class);
	 
	@Override
	public void requestDestroyed(ServletRequestEvent sre) {
		configHolder.remove();
	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		
		ServletContext servletContext = sre.getServletContext();
		// 获取当前 ClassLoader
		ClassLoader classLoader =  servletContext.getClassLoader();
		// get access to the Config instance
		ConfigProviderResolver configProviderResolver = ConfigProviderResolver.instance();
		Config config = configProviderResolver.getConfig(classLoader);
		logger.info("初始化 config , thread :{}",Thread.currentThread().getName());
		configHolder.set(config);
	}

	
	public static Config getConfig() {
        return configHolder.get();
    }

}
